import { memo, useEffect, useMemo, useState } from "react";
import ReservePopupStyle from "./style";
import {
  Button,
  Divider,
  DotLoading,
  Selector,
  Tabs,
  Tag,
  Toast,
} from "antd-mobile";
import {
  useGetTimetablesByCourse,
  useReserveCourse,
} from "../../../../service/timetable";
import { TimetableType } from "../../../../types/timetable/inex";
import { useGetNormalCardRecordsByCourse } from "../../../../service/cardRecord";
import { CardRecordType } from "../../../../types/cardRecord";
import dayjs from "dayjs";
import { weekLanguageMap } from "../../../../utils";
import Hr from "../../../../baseUI/hr";
import { CardType, CardTypeType } from "../../../../types/card";
import { CheckOutline, CloseOutline } from "antd-mobile-icons";

const ReservePopup = memo(
  (props: { courseId: string | undefined; closePopup: () => void }) => {
    const { courseId, closePopup } = props;
    const [timetables, setTimetables] = useState<TimetableType[]>();
    const [cardRecord, setCardRecord] = useState<CardRecordType[]>();
    const [selectTimetable, setSelectTimetable] = useState<string>();
    const [selectCard, setSelectCard] = useState<string>();

    const { getTimetablesByCourse, loading: timetableLoaing } =
      useGetTimetablesByCourse();
    const { getNormalCardRecordsByCourse, loading: cardsLoading } =
      useGetNormalCardRecordsByCourse();
    const { reserveCourse, loading: reserveCourseLoading } = useReserveCourse();

    useEffect(() => {
      if (courseId) {
        void getTimetablesByCourse(courseId).then((res) => {
          setTimetables(res.data);
        });
        void getNormalCardRecordsByCourse(courseId).then((res) => {
          setCardRecord(res.data);
        });
      } else {
        setSelectTimetable(undefined);
        setCardRecord(undefined);
      }
    }, [courseId]);

    const reserveBtnClick = () => {
      if (!selectCard || !selectTimetable) {
        Toast.show({
          icon: <CloseOutline />,
          content: "请选择课程和消费卡！",
        });
        return;
      }
      void reserveCourse(
        courseId!,
        selectCard,
        selectTimetable,
        timetables?.[0]!.orgId as string
      ).then((res) => {
        if (!res.code) {
          Toast.show({
            icon: <CloseOutline />,
            content: res.message,
          });
        } else {
          Toast.show({
            icon: <CheckOutline />,
            content: "预约成功",
          });
          closePopup();
        }
      });
    };

    const weeks = useMemo(() => {
      const arr = [];
      if (timetables) {
        // 获取到从当前日期到未来七天的排课
        for (let i = 1; i < 8; i++) {
          const day = dayjs().add(i, "day");
          const week = weekLanguageMap(day.format("dddd"));
          const time = timetables.filter((item) =>
            day.isSame(item.classDay, "day")
          );
          const orderTime = time?.map((item) => ({
            label: `${item.startTime.slice(0, 5)} - ${item.endTime.slice(
              0,
              5
            )}`,
            value: item.id,
          }));
          arr.push({
            week,
            orderTime,
          });
        }
      }
      return arr;
    }, [timetables]);
    const cards = useMemo(() => {
      if (cardRecord)
        return cardRecord.map((item) => {
          const card = JSON.parse(item.card) as CardType;
          return {
            value: item.id,
            label: (
              <div className="popupCard">
                <div className="cardTitle">
                  <Tag
                    className="cardType"
                    color={
                      card.type === CardTypeType.DURATION
                        ? "var(--themeColor1)"
                        : "var(--themeColor2)"
                    }
                  >
                    {card.type === CardTypeType.TIME ? "次数卡" : "时长卡"}
                  </Tag>{" "}
                  {card.name}
                </div>
                <div className="surplus">
                  {card.type === CardTypeType.TIME
                    ? `剩余次数 ${item.residueTime}`
                    : `有效期至 ${dayjs(item.endTime).format("YYYY-MM-DD")}`}
                </div>
              </div>
            ),
          };
        });
    }, [cardRecord]);
    return (
      <ReservePopupStyle>
        <Divider>选择预约时间(未来七天)</Divider>
        {timetableLoaing || weeks.length === 0 ? (
          <DotLoading color="primary" />
        ) : (
          <Tabs>
            {weeks?.map((item) => (
              <Tabs.Tab title={item.week} key={item.week}>
                {item.orderTime.length === 0 ? (
                  <span style={{ color: "#f02929" }}>该日期暂无排课</span>
                ) : (
                  <Selector
                    options={item.orderTime ?? []}
                    onChange={(arr) => {
                      setSelectTimetable(arr[0]);
                    }}
                  />
                )}
              </Tabs.Tab>
            ))}
          </Tabs>
        )}
        <Divider>选择消费卡</Divider>
        {cardsLoading ? (
          <DotLoading color="primary" />
        ) : (
          <Selector
            options={cards ?? []}
            columns={1}
            className="cardRecordSelector"
            onChange={(arr) => {
              setSelectCard(arr[0]);
            }}
          />
        )}
        <Hr />
        <Button
          loading={reserveCourseLoading}
          style={{ backgroundColor: "var(--themeColor1)", color: "white" }}
          onClick={reserveBtnClick}
        >
          立即预约
        </Button>
      </ReservePopupStyle>
    );
  }
);

export default ReservePopup;
